<template>
  <div style="box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)"> 
      <div style="height:80px;background:white" >
        <el-form ref="formQueryUser" label-position="right" label-width="80px" :model="formQueryUser" >
          <el-form-item 
          prop="username"
          label="用户名称:" 
          size="mini" 
          style="float:left;display: inline-block;margin-left: 100px;padding-top: 25px;"
          :rules="[
            { required: false, message: '请输入用户名称', trigger: 'blur' }
          ]"
          >
            <el-input v-model="formQueryUser.username"></el-input>
          </el-form-item>
          <el-form-item style="float:right;display: inline-block;padding-top: 25px;margin-right: 100px;" >
            <el-button  icon="el-icon-search" size="small" type="success" @click="selectUser()"  >查询</el-button> 
            <el-button icon="el-icon-refresh" @click="resetForm('formQueryUser')" size="small">重置</el-button>
          </el-form-item>
        </el-form>                       
      </div>
      <el-divider></el-divider>
      <div style="height:50px;background:white;padding-top: 25px;">
          <el-button size="small" @click="addUserDialog" icon="el-icon-zoom-in"  type="success"  style="float: left;margin-left: 50px;" >添加用户</el-button>
          <el-button size="small" @click="exportUser" icon="el-icon-search" type="primary" style="float: left ;margin-left: 35px;">导出用户</el-button>
          <el-button size="small" @click="exportSelectUser" icon="el-icon-search" type="primary" style="float: left;margin-left: 35px;">导出指定用户</el-button>        
      </div>
    <el-divider></el-divider> 
    <!--渲染数据  -->
    <div>
      <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" ></el-table-column>
      <el-table-column label="用户名" align="center">
        <template slot-scope="scope">
          <div>{{ scope.row.username }}</div>
        </template>
      </el-table-column>
      <el-table-column label="用户姓名" align="center">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <p>用户姓名: {{ scope.row.personName }}</p>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium">{{ scope.row.personName }}</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="联系电话" align="center">
        <template slot-scope="scope">
          <p>{{ scope.row.telephone }}</p>
        </template>
      </el-table-column>
      <el-table-column label="联系邮箱" align="center">
        <template slot-scope="scope">
          <div>{{ scope.row.email }}</div>
        </template>
      </el-table-column>
      <el-table-column label="生日" align="center">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 10px">{{$moment(scope.row.birthday).format('YYYY-MM-DD')}}</span>
        </template>
      </el-table-column>
      <el-table-column label="职位" align="center">
        <template slot-scope="scope" >
          <div v-for=" (role) in scope.row.roleList" :key="role.roleId" >{{
            role.roleName
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="用户状态" align="center">
        <template slot-scope="scope">
          <!-- <p v-if="scope.row.states===0">可用</p>
          <p v-else>不可用</p> -->
        <el-switch
          v-model="scope.row.states"
          :active-value="1"
          :inactive-value="0"
          active-color="#13ce66"
          inactive-color="#ff4949">
        </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="用户创建时间" align="center">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 10px">{{$moment(scope.row.createTime).format('YYYY-MM-DD')}}</span>
        </template>
      </el-table-column>      
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="checkUser(scope.row.userId)">查看</el-button>
          <el-button type="text" @click="updateUserDialog(scope.row.userId)">编辑</el-button>   
          <el-button type="text" @click="updatePasswordDialog(scope.row.userId)">重置密码</el-button> 
          <el-button type="text" :disabled="scope.row.states===0" @click="checkQueryRoleDialog(scope.row.userId)">角色设置</el-button>    
          <el-button type="text" @click="queryUserRelationMenu(scope.row.userId)">查看权限</el-button>                                
        </template>
      </el-table-column>
    </el-table>
    </div>
    <div>
      <!--prev表示上一页，next为下一页，pager表示页码列表,total表示总条目数，size用于设置每页显示的页码数量。-->
      <el-pagination
        background
        layout="total,prev,sizes, pager, next,jumper"
        :total="total"
        :page-sizes="[5, 10, 15, 20]"
        :page-size.sync="formSearch.pageSize"
        :current-page.sync="formSearch.pageNum"
        @current-change="getPage"
        @size-change="getPage"
        style="float: right">
      </el-pagination>
    </div>
    <!-- 添加用户 -->
    <div>
      <el-dialog title="添加用户"  :visible.sync="addUserVisible"  :close-on-click-modal="false" center  >
        <el-divider></el-divider>
        <el-form ref="formAddUser" :model="formAddUser" :rules="formAddUserRules" center>
          <el-form-item label="账户名称" label-width="140px" prop="userName">
            <el-input v-model="formAddUser.userName" placeholder=" 请输入账户名称" ></el-input>
          </el-form-item>
          <el-form-item label="账户密码" label-width="140px" prop="password">
            <el-input placeholder="请输入账户密码" v-model="formAddUser.password" show-password></el-input>
          </el-form-item>
          <el-form-item label="用户姓名" label-width="140px" prop="personName">
            <el-input v-model="formAddUser.personName" placeholder="请输入用户姓名"></el-input>
          </el-form-item>          
          <el-form-item label="用户职位" label-width="140px">
            <el-select v-model="formAddUser.description" placeholder="请选择用户职位">
              <el-option v-for="role in roleList" :label="role.roleName" :key="role.roleId" :value="role.roleId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="用户生日" label-width="140px" prop="birthday">
            <el-date-picker v-model="formAddUser.birthday" type="datetime" placeholder="请选择用户生日">
            </el-date-picker>
          </el-form-item>          
          <el-form-item label="用户电话" label-width="140px" prop="telephone">
            <el-input v-model="formAddUser.telephone" placeholder="请输入用户电话"></el-input>
          </el-form-item>
          <el-form-item label="用户邮箱" label-width="140px" prop="email">
            <el-input v-model="formAddUser.email" placeholder="请输入用户邮箱"></el-input>
          </el-form-item>    
          <el-form-item label="用户状态" label-width="140px">
            <el-select v-model="formAddUser.states" placeholder="请选择用户状态">
              <el-option label="启用" value="1"></el-option>
              <el-option label="停用" value="0"></el-option>
            </el-select>
          </el-form-item>

          <!-- <el-form-item label="用户头像" label-width="140px" prop="email">
            <el-upload
              class="avatar-uploader"
              accept="image/jpg,image/jpeg,image/png"
              :action="handleImageURL()"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              style="">
              <img title="点击头像进行修改" v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item >  -->
            <el-divider></el-divider>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="addUserVisible = false">取 消</el-button>
          <el-button size="small" type="primary" @click="saveUser">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 查看用户 -->
    <div>
      <el-dialog title="查看用户"  :visible.sync="checkUserVisible"  :close-on-click-modal="false" center  >
        <el-form ref="cheakUserData" :model="cheakUserData"  center>
          <el-form-item label="账户名称:" label-width="140px" >
            <el-input disabled v-model="cheakUserData.username" ></el-input>
          </el-form-item>
          <el-form-item label="用户姓名:" label-width="140px" >
            <el-input disabled v-model="cheakUserData.personName"></el-input>
          </el-form-item>
          <el-form-item label="用户类型:" label-width="140px">
            <el-select disabled  v-model="cheakUserData.description" >
              <el-option label="管理员" :value="1"></el-option>
              <el-option label="普通用户" :value="2"></el-option>
              <el-option label="客户" :value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="用户生日:" label-width="140px" >
            <el-input disabled v-model="cheakUserData.birthday"></el-input>
          </el-form-item>
          <el-form-item label="用户电话:" label-width="140px" >
            <el-input disabled v-model="cheakUserData.telephone"></el-input>
          </el-form-item>   
          <el-form-item label="用户邮箱:" label-width="140px" >
            <el-input disabled v-model="cheakUserData.email"></el-input>
          </el-form-item>   
          <el-form-item label="用户状态:" label-width="140px">
            <el-select disabled  v-model="cheakUserData.states" >
              <el-option label="可用" :value="1"></el-option>
              <el-option label="不可用" :value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
    <!--编辑用户 -->
    <div>
      <el-dialog title="修改用户"  :visible.sync="updateUserVisible" :close-on-click-modal="false" center  >
        <el-divider></el-divider>
        <el-form ref="updateUserData" :model="updateUserData" :rules="formAddUserRules" center>
          <el-form-item label="账户名称" label-width="140px" prop="userName">
            <el-input v-model="updateUserData.username" placeholder=" 请输入账户名称" ></el-input>
            <span style="color:red;">注意：谨慎修改，该账号作为登录账号使用！</span>
          </el-form-item>
          <el-form-item label="用户姓名" label-width="140px" prop="personName">
            <el-input v-model="updateUserData.personName" placeholder="请输入用户姓名"></el-input>
          </el-form-item>          
          <el-form-item label="用户类型" label-width="140px">
            <el-select v-model="updateUserData.description" placeholder="请选择用户类型">
              <el-option label="普通管理员" :value="1"></el-option>
              <el-option label="游客" :value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="用户生日" label-width="140px" prop="birthday">
            <el-date-picker v-model="updateUserData.birthday" type="datetime" placeholder="请选择用户生日">
            </el-date-picker>
          </el-form-item>          
          <el-form-item label="用户电话" label-width="140px" prop="telephone">
            <el-input v-model="updateUserData.telephone" placeholder="请输入用户电话"></el-input>
          </el-form-item>
          <el-form-item label="用户邮箱" label-width="140px" prop="email">
            <el-input v-model="updateUserData.email" placeholder="请输入用户邮箱"></el-input>
          </el-form-item>    
          <el-form-item label="用户状态" label-width="140px">
            <el-select v-model="updateUserData.states" placeholder="请选择用户状态">
              <el-option label="启用" :value="1"></el-option>
              <el-option label="停用" :value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="updateUserVisible = false">取 消</el-button>
          <el-button size="small" type="primary" @click="updateUser">确 定</el-button>
        </div>
      </el-dialog>  
    </div>
    <!--重置密码-->
    <div>
      <el-dialog title="重置密码"  :visible.sync="updatePasswordVisible" :close-on-click-modal="false" center  >
        <el-divider></el-divider>
        <el-form ref="updatePasswordData" :model="updatePasswordData" :rules="updatePasswordRules" status-icon center>
          <el-form-item label="账户名称" label-width="140px" >
            <el-input disabled v-model="updatePasswordByUsername.username" placeholder=" 请输入账户名称" ></el-input>
          </el-form-item>
          <el-form-item label="新密码" label-width="140px" prop="password">
            <el-input type="password" v-model="updatePasswordData.password" placeholder=" 请输入新密码" show-password ></el-input>
          </el-form-item>
          <el-form-item label="确认密码" label-width="140px" prop="checkPass">
            <el-input type="password" v-model="updatePasswordData.checkPass" placeholder=" 请再次输入密码" show-password ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="updatePasswordVisible = false">取 消</el-button>
          <el-button size="small" type="primary" @click="updatePassword">确 定</el-button>
        </div>
      </el-dialog>  
    </div>
    <!-- 角色设置--查看用户当前具有的角色 -->
    <div>
      <el-dialog title="关联角色"  :visible.sync="queryRoleVisible"  :close-on-click-modal="false" center  >
        <span style="color:red;">**当前用户具有的角色，支持用户对应多种角色</span>
        <el-button type="primary" plain @click="checkRoleDialog()" style="float:right;" >添加</el-button>
        <el-divider></el-divider>
          <div>
            <el-table  :data="tableQueryRoleData" style="width: 100%" >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="角色名称" width="130">
              <template slot-scope="scope">
                <div>{{ scope.row.roleName }}</div>
              </template>
            </el-table-column>
            <el-table-column label="角色状态" width="150">
              <template slot-scope="scope">
              <el-switch
                v-model="scope.row.states"
                :active-value="1"
                :inactive-value="0"
                active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
              </template>
            </el-table-column>
            <el-table-column label="角色创建时间" width="180">
              <template slot-scope="scope">
                <i class="el-icon-time"></i>
                <span style="margin-left: 10px">{{$moment(scope.row.createTime).format('YYYY-MM-DD')}}</span>
              </template>
            </el-table-column>      
            <el-table-column label="操作" width="180">
              <template slot-scope="scope">
                <el-button type="text" @click="deleteUserRoleRelation(scope.row.roleId)">删除</el-button>                                
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 角色设置--给用户添加角色内层弹窗 -->
          <el-dialog title="添加角色"  :visible.sync="addRoleVisible"  :close-on-click-modal="false" center append-to-body   >
            <span style="color:red;">**当前用户具有的角色，不可取消选中</span>
            <el-divider></el-divider>
                <el-table ref="multipleTable" :data="tableRoleData" style="width: 100%"  @selection-change="handleSelectionRoleChange" @select='selectSingle'>
                  <el-table-column type="selection" width="55" :selectable='selectEnable'></el-table-column>
                  <el-table-column label="角色名称" width="200">
                    <template slot-scope="scope">
                      <div>{{ scope.row.roleName }}</div>
                    </template>
                  </el-table-column>
                  <el-table-column label="角色状态" width="200">
                    <template slot-scope="scope">
                    <el-switch
                      v-model="scope.row.states"
                      :active-value="1"
                      :inactive-value="0"
                      active-color="#13ce66"
                      inactive-color="#ff4949">
                    </el-switch>
                    </template>
                  </el-table-column>
                  <el-table-column label="角色创建时间" width="180">
                    <template slot-scope="scope">
                      <i class="el-icon-time"></i>
                      <span style="margin-left: 10px">{{$moment(scope.row.createTime).format('YYYY-MM-DD')}}</span>
                    </template>
                  </el-table-column>      
                </el-table>
              <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="addRoleVisible = false">取 消</el-button>
                <el-button size="small" type="primary" @click="addUserRelationRole">确 定</el-button>
              </div>
          </el-dialog>      
      </el-dialog>      
    </div>
    <!-- 查看当前用户所具有的菜单权限 -->
    <div>
      <el-dialog title="查看权限"  :visible.sync="queryUserRelationMenuVisible"  :close-on-click-modal="false" center  >
        <div style=" box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);">
          <el-tree
              ref="tree"
              :data="data"
              :show-checkbox="true"
              node-key="menuId"
              default-expand-all 
              :expand-on-click-node="false"
              :props="defaultProps"
              :default-checked-keys="checkMenuArray">
              <span class="custom-tree-node show-hide" slot-scope="{ node, data }">
                <span>
                    <i v-if="data.menuType==1" class="el-icon-folder-opened"></i>
                    <i v-else-if="data.menuType==2" class="el-icon-document-remove"></i>
                    <i v-else-if="data.menuType==3" class="el-icon-thumb"></i>
                {{ node.label }}
                </span>
              </span>
          </el-tree>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="cancelAdminVisible">取 消</el-button>
          <el-button size="small" type="primary" @click="cancelAdminVisible">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import user from '../../api/user'
import role from '../../api/role'
import menu from '../../api/menu'


export default {
  name: "user",
  data(){
    //自定义密码校验规则
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.updatePasswordData.checkPass !== '') {
            this.$refs.updatePasswordData.validateField('checkPass');
          }
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.updatePasswordData.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
    return{
      tableData:[],
      total:0,
      formSearch:{
        pageNum:1,
        pageSize:10
      },
      //批量删除
      userIdsArray:[],
      userIds:'',
      //角色选中状态，添加角色
      roleIdsArray:[],
      roleIds:'',
      //添加用户
      addUserVisible:false,
      formAddUser:{},
      roleList:{},
      //查看用户
      checkUserVisible:false,
      cheakUserData:{},
      //修改客户
      updateUserVisible:false,
      updateUserData:{},
      //修改密码
      updatePasswordVisible:false,
      updatePasswordByUsername:{},
      updatePasswordData:{
        userId:'',
        password:'',
        checkPass:''
      },
      //修改密码校验规则
      updatePasswordRules:{
        password: [
          {required:true, validator: validatePass, trigger: 'blur' },
          { min:5, max:16, message:'长度在5到16个任意字符', trigger:'blur'}
        ],
        checkPass: [
          {required:true,validator: validatePass2, trigger: 'blur' },
          { min:5, max:16, message:'长度在5到16个任意字符', trigger:'blur'}
        ],
      },
      //根据用户名称查询
      formQueryUser:{
        pageNum:1,
        pageSize:10,
        username:''
      },
      //添加用户规则
      formAddUserRules:{
        userName: [{required:true, message:"请输入账户名称",trigger:'blur'}],
        password: [{required:true, message:"请输入账户密码",trigger:'blur'}],
        personName: [{required:true, message:"请输入用户姓名",trigger:'blur'}],
        birthday: [{required:true, message:"请选择用户生日",trigger:'blur'}],                        
        email: [
            { required: true, message: '请填写E-mail', trigger: 'blur' },
            { pattern: /^([a-zA-Z0-9]+[-_\.]?)+@[a-zA-Z0-9]+\.[a-z]+$/, message: '请输入正确的E-mail', trigger: 'blur' }],
        telephone:[
            { required: true, message: '请输入手机号码', trigger: 'blur' },
            { pattern:/^1[12345789]\d{9}$/, message: '请输入正确的手机号码'}],
    
      },
      //导出用户
      exportUserURL:'',
      //查询当前用户所拥有的角色
      queryRoleVisible:false,
      fromQueryUserRelationRole:{
        userId:'',
      },
      //角色管理
      addRoleVisible:false,
      tableRoleData:[],
      tableQueryRoleData:[],
      //给当前用户添加角色
      fromRoleData:{
        roleIds:'',
        userId:''
      },
      //删除当前用户关联角色
      deleteFromRoleData:{
        roleIds:'',
        userId:''
      },

      //查看当前用户关联菜单权限
      queryUserRelationMenuVisible:false,
      //tree节点
      data: [],
      defaultProps: {
          id:'menuId',
          children: 'children',
          label: 'menuName'
      },
      //回显菜单信息
      checkMenuFrom:{},
      //默认选中的节点数组
      checkMenuArray:[],
      //查询用户关联菜单对象
      queryFromUserRelationMenuData:{
        userId:''
      },

    }
  },
  created(){
    this.getPage();
  },
  

  methods:{
    //用户分页
    async getPage(){
      const res=await user.queryAllUser(this.formSearch);
      if(res.data.code=== '000'){
        this.tableData=res.data.data.records;
        this.total=res.data.data.total;
      }
    },
    //多选框选中状态,将userid转换成一个字符串
    handleSelectionChange(val){
      this.userIdsArray=val;
      const idList = [];
      for (const v of this.userIdsArray) {
        idList.push(v.userId)
      };
      this.userIds=idList.join(',');
      // console.log(this.userIds);
    },
    //多选框选中状态,将roleid转换成一个字符串
    handleSelectionRoleChange(val){
      this.roleIdsArray=val;
      const idList = [];
      for (const v of this.roleIdsArray) {
        idList.push(v.roleId)
      };
      this.fromRoleData.roleIds=idList.join(',');
      // console.log(this.fromRoleData.roleIds);
    },
    //多选框禁止选中
    selectEnable(row, rowIndex) {
      if (row.states===0) {
        return false
      } else {
        return true// 不禁用
      }
    },
    //多选框选中状态不可取消
    selectSingle(selection,row){
      //默认勾选
      this.$nextTick(()=>{
        try {
          this.tableQueryRoleData.forEach((tqrd) =>{
          this.tableRoleData.forEach((trd)=>{
            if(tqrd.roleId == trd.roleId){
              this.$refs.multipleTable.toggleRowSelection(trd,true)
            }
            })
          })
        } catch (error) {
            
        }
      });
    },
    //添加用户弹框
    addUserDialog(){
      this.addUserVisible=true;
      try {
        this.$refs['formAddUser'].resetFields()
      } catch (err) {

      }
      this.queryAllRole()
    },
    //添加用户
    saveUser(){
      this.$refs.formAddUser.validate((valid) => {
        if (valid) {
          user.saveUser(this.formAddUser).then(res =>{
            if(res.data.code=== '000'){
              this.addUserVisible=false,
              this.$message.success("添加成功")
              this.getPage();
            }else{
              this.$message.error("添加失败")
            }
          })
        } else {
          return false;
        }
      });

    },
    //查看用户
    async checkUser(userId){
      this.checkUserVisible=true;
      const res=await user.selectUserByUserId({userId:userId});
      if(res.data.code=== '000'){
        this.cheakUserData=res.data.data;
        this.cheakUserData.birthday=this.$moment(res.data.data.birthday).format('YYYY-MM-DD')
      }
    },
    //修改用户,第一步查出要修改用户的数据
    async updateUserDialog(userId){
      this.updateUserVisible=true;
      const res=await user.selectUserByUserId({userId:userId});
      if(res.data.code=== '000'){
        this.updateUserData=res.data.data;
      }
    },
    //修改用户，第二步，发情修改请求
    async updateUser(){
      const res=await user.updateUserByUserId(this.updateUserData);   
      if(res.data.code==='000'){
        this.updateUserVisible=false;
        this.$message({
          message: '修改成功',
          type: 'success'
        }),
        this.getPage()//请求刷新，重新刷新页面
      }else{
        this.$message.error("修改失败");
      }
    },
    //重置密码弹窗
    async updatePasswordDialog(userId){
      this.updatePasswordVisible=true;
      try {
        this.$refs['updatePasswordData'].resetFields()
      } catch (err) {

      }
      const res=await user.selectUserByUserId({userId:userId});
      if(res.data.code=== '000'){
        this.updatePasswordByUsername=res.data.data;
        this.updatePasswordData.userId=res.data.data.userId
      }
    },
    //重置密码第二步
    updatePassword(){
      this.$refs.updatePasswordData.validate((valid) => {
        if (valid) {
          user.updatePasswordByUserId(this.updatePasswordData)
          .then(res =>{
            if(res.data.code==='000'){
              this.updatePasswordVisible=false;
              this.$message({
                message: '修改成功',
                type: 'success'
              }),
              this.getPage()//请求刷新，重新刷新页面
          }else{
              this.$message.error("修改失败");
          }
          })
        } else {
          return false;
        }
      });
    },
    //根据用户名称模糊查询
    async selectUser(){
      const res=await user.queryAllUser(this.formQueryUser);
      if(res.data.code === '000'){
        this.tableData=res.data.data.records;
        this.total=res.data.data.total;
      }
    },

    //导出用户
    async exportUser(){
      const res=await user.exportUser(this.formQueryUser);
      if(res.data.code==='000'){
        this.exportCustomerUrl=res.data.data;
        this.download(this.exportCustomerUrl);
        this.$message({
          message: '导出成功',
          type: 'success'
        })
      }else{
        this.$message.error("导出失败")
      }
    },
    //导出指定用户
    exportSelectUser(){

    },
    //下载
    download(url){
      var iframe = document.createElement('iframe')
      iframe.style.display = 'none'
      iframe.src = url
      document.body.appendChild(iframe)
    },
    //重置表单,表单必须有ref属性的值，还要有数据绑定的数据源，还要有验证规则,prop都不能少，才可以实现关闭表单清空内容
    resetForm(formQueryUser) {
      this.$refs[formQueryUser].resetFields();
    },
    //查询当前用户所拥有的角色弹窗
    checkQueryRoleDialog(userId){
      this.fromQueryUserRelationRole.userId=userId;
      this.fromRoleData.userId=userId;
      this.deleteFromRoleData.userId=userId;
      this.queryRoleVisible=true;
      this.getQueryRolePage();
    },
    //角色设置第一步：查询当前用户所拥有的角色请求
    async getQueryRolePage(){
      const res=await user.queryUserRelationAllRole(this.fromQueryUserRelationRole);
      if(res.data.code === '000'){
        this.tableQueryRoleData=res.data.data.roleList;
      }else{
        this.tableQueryRoleData=null
      }
    },
    //添加角色弹窗
    checkRoleDialog(userId){
      this.addRoleVisible=true;
      this.getRolePage();
    },
    //角色设置第二步：查询所有角色
    async getRolePage(){
      const res=await role.queryAllRole(this.formSearch);
      if(res.data.code==='000'){        
        this.tableRoleData=res.data.data.records;
        //默认勾选
        this.$nextTick(()=>{
          try {
            this.tableQueryRoleData.forEach((tqrd) =>{
            this.tableRoleData.forEach((trd)=>{
              if(tqrd.roleId == trd.roleId){
                this.$refs.multipleTable.toggleRowSelection(trd,true)
              }
            })
          })
          } catch (error) {
            
          }
        });
      }
    },
    //角色设置第三步：给当前用户添加角色请求
    async addUserRelationRole(){
      if(this.fromRoleData.roleIds === ''){
        this.$message.error("请选择要添加的角色，不可以取消默认选中");
        this.getRolePage();
        return false;
      }
      const res=await user.addUserRelationRole(this.fromRoleData);
      if(res.data.code === '000'){
        this.addRoleVisible=false;
        this.$message.success("添加成功");
        this.getQueryRolePage();
      }
    },
    //删除用户关联角色
    
    deleteUserRoleRelation(roleId){
      this.deleteFromRoleData.roleId=roleId;
      this.$confirm("确定删除这条员工信息么","提示",{
        confirmButtonText:'确定',
        cancelButtonText:'取消'
      }).then(()=>{
        user.deleteUserRelationRole(this.deleteFromRoleData).then(res =>{
          if(res.data.code==='000'){
            this.getQueryRolePage();
            this.$message.success("删除成功")
          }else{
            this.$message.error("删除失败")
          }
        })

      })
    },
    //查看权限弹窗
    queryUserRelationMenu(userId){
      this.queryUserRelationMenuVisible=true;
      this.queryFromUserRelationMenuData.userId=userId;
      this.queryAllMenu();
      this.queryUserRelationAllMenu();
    },
    //关闭查看权限弹窗
    cancelAdminVisible(){
      this.queryUserRelationMenuVisible=false;
      this.$refs.tree.setCheckedKeys([])
    },
    //获取所有菜单
    async queryAllMenu(){
        const res=await menu.queruAllMenu();
        if(res.data.code==='000'){
            this.data=res.data.data
        }
    },
    //查看权限第三步，获取用户关联菜单
    async queryUserRelationAllMenu(){
      const res=await user.queryUserRelationAllMenu(this.queryFromUserRelationMenuData);
      if(res.data.code === '000'){
          this.checkMenuArray.length=0;
          this.checkMenuFrom=res.data.data
          this.checkMenuFrom.forEach(menu =>{
            if(menu.children.length > 0){
              menu.children.forEach( menus =>{
                if(menus.children.length > 0){
                  menus.children.forEach(men =>{
                    if(men.children.length > 0){
                        men.children.forEach(me =>{
                          if(me.children.length > 0){
                          }else{
                            this.checkMenuArray.push(me.menuId);
                          }
                        })
                    }else{
                      this.checkMenuArray.push(men.menuId);
                    }
                  })
                }else{
                  this.checkMenuArray.push(menus.menuId);
                }
              })
            }else{
              this.checkMenuArray.push(menu.menuId);
            }
          })
      }else if(res.data.code==='400'){
        this.$message.warning(res.data.msg)
      }
    },
    //查询所有角色
    async queryAllRole(){
      const res = await role.list()
      if(res.data.code === '000'){
        this.roleList = res.data.data
      }
    },
  }
}
</script>

<style>

.el-divider {
    background-color: white;
}
</style>
